package com.laihui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.laihui.Constants;
import com.laihui.MyApplication;
import com.laihui.base.BaseActivity;
import com.laihui.dialog.Loading;
import com.laihui.entity.MemberBank;
import com.laihui.entity.RetMap;
import com.laihui.model.Recharge;
import com.laihui.utils.ToastUtil;
import com.laihui.utils.XmlPullUtils;
import com.laihui.view.TopBar;
import com.fuiou.mobile.FyPay;
import com.fuiou.mobile.FyPayCallBack;
import com.fuiou.mobile.bean.MchantMsgBean;
import com.fuiou.mobile.util.EncryptUtils;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 充值页面
 */
public class RechargeActivity extends BaseActivity {

    @BindView(R.id.topbar)//topbar
            TopBar topbar;
    @BindView(R.id.iv_bank_logo)//银行logo
            ImageView ivBankLogo;
    @BindView(R.id.tv_bank_card_number)//银行卡号
            TextView tvBankCardNumber;
    @BindView(R.id.et_recharge_money)//充值输入的金额
            EditText etRechargeMoney;
    @BindView(R.id.btn_submit)//提交按钮
            Button btnSubmit;
    @BindView(R.id.tv_bank_type)//银行名字
            TextView tvBankType;
    /*@BindView(R.id.et_bill_number)
    EditText etBillNumber;*/
    private Activity mActivity;
    private MyApplication application;
    private static final String TAG = "RechargeActivity";
    //private String cardNo;//银行卡号-
    private String mchntCd;//商户号-
    private String amt;//金额-
    private String backUrl;//回调地址-
    private String cardNo;//银行卡号-
    private String orderId;//商户订单号-
    private String IDcardType;//证件类型-
    private String userId;//-
    private String IDNo;//证件号-
    private String userName;//名字-
    private String signKey;
    private String sdkSignTp;//-
    private String sdkType;//商户秘钥
    private String sdkVersion;//sdk版本号-
    private String payType;
    private String key;

    @Override
    public void init() {
        mActivity = RechargeActivity.this;
        application = (MyApplication) getApplication();
        topbar.setOnTopbarClickListener(new TopBar.topbarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void rightClick() {

            }
        });
        bankcard();

        FyPay.setDev(true);
        FyPay.init(RechargeActivity.this);
    }

    private void bankcard() {

        Map<String, String> map = new HashMap<>();
        map.put("member_id", application.userId);
        application.apiService.isBankBind(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<MemberBank>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError: "+e.toString());
                    }

                    @Override
                    public void onNext(MemberBank memberBank) {
                        tvBankType.setText(memberBank.item.bank);
                        Glide.with(mActivity).load(Constants.BASE_URL+memberBank.item.bank_img_mobile).into(ivBankLogo);
Log.e("rechagrebank",memberBank.item.bank_cardno+"");
                        //tvBankNumber.setText(bankCard.getBankCard().getBank_cardno());
                        if (memberBank.item.bank_cardno.length()==16){
                            tvBankCardNumber.setText("**************"+memberBank.item.bank_cardno.substring(12,16));
                        }else{
                            tvBankCardNumber.setText("**************"+memberBank.item.bank_cardno.substring(15,19));
                        }

                    }
                });


    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_recharge;
    }

    @Override
    public Activity bindActivity() {
        return this;
    }


    @OnClick({R.id.btn_submit,R.id.tv_help})
    public void onClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_submit:

                HashMap map = new HashMap();
                map.put("member_id",application.userId);
                map.put("money",etRechargeMoney.getText().toString());
                application.apiService.rechargeForm(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<Recharge>() {
                            @Override
                            public void onCompleted() {
                                Loading.dismiss();
                            }

                            @Override
                            public void onError(Throwable e) {
                                Loading.dismiss();
                                Log.e(TAG, "onError: "+e.toString());
                            }

                            @Override
                            public void onNext(Recharge recharge) {
                                if(recharge.getStatus().equals("0")){
                                    ToastUtil.showToast(RechargeActivity.this,recharge.getMessage());
                                }
                                Loading.dismiss();
                                mchntCd = recharge.getFyRechargeWebBean().getMchnt_cd();
                                amt = recharge.getFyRechargeWebBean().getAmt();
                                backUrl = recharge.getFyRechargeWebBean().getBack_url();
                                orderId = recharge.getFyRechargeWebBean().getMchnt_order_id();
                                IDcardType = recharge.getFyRechargeWebBean().getId_type();
                                IDNo = recharge.getFyRechargeWebBean().getId_no();
                                userId = application.userId;
                                userName = recharge.getFyRechargeWebBean().getName();
                                sdkVersion = recharge.getFyRechargeWebBean().getVersion();
                                sdkSignTp = "MD5";
                                sdkType = "02";
                                key = recharge.key;
                                signKey = EncryptUtils.md5Encrypt(sdkType+"|"+sdkVersion+/*"|"+0000+*/"|"+mchntCd+"|"+orderId+"|"+orderId+"|"+amt+"|"+ recharge.getFyRechargeWebBean().getBank_card()+"|"+key);
                                final MchantMsgBean bean = new MchantMsgBean();
                                bean.setMchntCd(mchntCd);
                                bean.setAmt(amt);
                                bean.setCardNo( recharge.getFyRechargeWebBean().getBank_card());
                                bean.setIDcardType(IDcardType);
                                bean.setOrderId(orderId);
                                bean.setUserId(userId);
                                bean.setIDNo(IDNo);
                                bean.setUserName(userName);
                                bean.setBackUrl(backUrl);
                                bean.setSignKey(signKey);
                                bean.setKey(key);
                                bean.setPayType("mobilePay");
                                int i = FyPay.pay(RechargeActivity.this, bean, new FyPayCallBack() {
                                            @Override
                                            public void onPayComplete(String rspCode, String rspDesc, Bundle extraData) {
                                                Log.d(TAG, "onPayComplete: "+rspCode+rspDesc);
                                                Log.e(TAG, "rspCode = " + rspCode + " ; rspDesc = " + rspDesc);
                                            }

                                            @Override
                                            public void onPayBackMessage(String paramString) {
// 支付异常处理，商户根据返回的paramString（参数参考表3.2）自行解析做界面展示，这里不再做技术解析说明！
                                                final HashMap dto = XmlPullUtils.getResponse(paramString);
                                                Log.e(TAG, "onPayBackMessage >>>" + paramString);

                                                Map<String,String> reqmap = new HashMap<>();

                                                // map.put("RESPONSEMSG",dto.getRESPONSEMSG());
//                                                Log.e(TAG, "onPayComplete: "+rspCode );
//                                                Log.e(TAG, "onPayComplete: "+orderId );
//                                                Log.e(TAG, "onPayComplete: "+amt );
                                                application.apiService.rechargeNotify(dto)
                                                        .subscribeOn(Schedulers.io())
                                                        .observeOn(AndroidSchedulers.mainThread())
                                                        .subscribe(new Subscriber<RetMap>() {
                                                            @Override
                                                            public void onCompleted() {

                                                            }

                                                            @Override
                                                            public void onError(Throwable e) {

                                                            }

                                                            @Override
                                                            public void onNext(RetMap retmap) {
                                                                ToastUtil.showToast(mActivity,retmap.message);
                                                               finish();
                                                            }
                                                        });

                                            }
                                        });
                            }
                        });
//                recharge();
                break;


            case R.id.tv_help:
                startActivity(new Intent(mActivity, ActivityHelp.class));
                break;


        }
    }


}
